package se.mbaeumer.fxtodo.gui;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import se.mbaeumer.fxtodo.core.model.Task;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Orientation;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class DateStage extends Stage {

	private Group root = new Group();
	private Scene scene;
	private TextField txtDateField;
	private Button btnSubmit;
	private FlowPane flow;
	private Label lblResult;
	private Task task;
	
	public DateStage(Task task){
		super();
		this.task = task;
		this.scene = new Scene(this.root, 150, 75, Color.BEIGE);
		this.setTitle("Pick a date");
		this.setScene(this.scene);
		
		this.setResizable(false);
		this.initFlowPane();
		this.initTextField();
		this.initSubmitButton();
		this.initLabel();
	}
	
	private void initFlowPane(){
		this.flow = new FlowPane();
		this.flow.setOrientation(Orientation.VERTICAL);
		this.root.getChildren().add(this.flow);
	}
	
	private void initTextField(){
		this.txtDateField = new TextField();
		// TODO: Use constants instead of hard-coded strings
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		this.txtDateField.setText(df.format(this.task.getDueDate()));
		this.flow.getChildren().add(this.txtDateField);
	}
	
	private void initSubmitButton(){
		this.btnSubmit = new Button("Submit");
		this.btnSubmit.setOnAction(new EventHandler<ActionEvent>(){

			@Override
			public void handle(ActionEvent arg0) {
				// TODO Auto-generated method stub
				processInput();
			}
			
		});
		this.flow.getChildren().add(this.btnSubmit);
	}
	
	private void initLabel(){
		this.lblResult = new Label();
		this.flow.getChildren().add(this.lblResult);
	}
	
	private void processInput(){
		// TODO: Use constants instead of hard-coded strings
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date date = new Date();
		
		try {
			date = df.parse(this.txtDateField.getText());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			this.lblResult.setText("An internal error occured!");
			return;
		}
		// check if the date is in the past
		if (date.before(new Date())){
			this.lblResult.setText("The date is in the past!");
			return;
		}
		this.lblResult.setText("OK");
		this.task.setDueDate(date);
		this.close();
		//this.lblResult.setText(date.toString());
	}

	public Task getTask() {
		return task;
	}

	public void setTask(Task task) {
		this.task = task;
	}
	
}
